require "lib/utils.rb"

ratingFiles = [];
tourneyDate = [];

$argN = 0;
while(ARGV[$argN])
	ratingFiles << getIntegerRatingsFromFile(ARGV[$argN])	
	tourneyDate << parseTourneyDate(ARGV[$argN])
	$argN+=1
end

ratingFilesForSort = getRatingsFromFile(ARGV[$argN-1])
sortedPlayers = ratingFilesForSort.sort{|a,b| b[1] <=> a[1]}.map{ |player| player[0] }
sortedPlayers.each {|name|
	for i in 0..ratingFiles.length-1
		ratingFiles[i][name] = 0 if(!ratingFiles[i][name])
	end
}

def getGraphURLForPlayers(playerNames, ratings, tourneyDates, title)

	lastRatingIndex = ratings.length-1
	
	maxRating = 0
	minRating = 1000
	for i in 0..lastRatingIndex
		tmpArray = ratings[i].collect{|a,b| b if playerNames.include? a}.compact!
		maxRating = (tmpArray + [maxRating]).max
		minRating = (tmpArray + [minRating]).min
	end
	
	maxRating = (maxRating/10)*10 + 10;
	minRating = (minRating/10)*10;
	
	playerRatings = {}
	playerNames.each {|name|
		for i in 0..lastRatingIndex
			playerRatings[name] = [] if(!playerRatings[name])
			playerRatings[name] << ratings[i][name]
		end
	}
	
	playersNum = playerNames.length
	#chartColors = ["EE0000","00EE00","0000EE","FFFF00","FF00FF","00FFFF","555555","770000","007700","000077"]
	chartColors = ["EE0000","00EE00","0000EE","FFFF00","FF00FF","00FFFF","AA0000","00AA00","0000AA","00AAAA"]
	lineTypes = ["2,1,0", "2,1,0", "2,1,0", "2,1,0", "2,1,0", "2,1,0", "2,6,3","2,6,3","2,6,3","2,6,3"]
	
	chartString = "http://chart.apis.google.com/chart?cht=lc&chs=600x300&chds=#{minRating},#{maxRating}"
	chartString+="&chdlp=r&chf=c,lg,0,76A4FB,1,ffffff,0|bg,s,EFEFEF&chxt=x,y,r"
	chartString+="&chtt=#{title}"
	yAxisLables = (minRating/10..maxRating/10).map{|x| 10*x if(x%2==0)}.join("|")
	xAxisLables = tourneyDates.join("|")
	chartString+="&chxl=1:|#{yAxisLables}|2:|#{yAxisLables}|0:|#{xAxisLables}"	
	chartString+="&chls="+lineTypes[0..playersNum-1].join("|")
	chartString+="&chco="+chartColors[0..playersNum-1].join(",")
	chartString+="&chdl="+playerNames.join("|")
	chartString+="&chd=t:" + playerNames.map{|name| playerRatings[name].join(",")}.join("|")
	chartString
end

puts "<center>"
for i in 0..4
	startId = i*10
	endId = (i+1)*10-1
	title = "Players from #{startId+1} to #{endId+1}"
	puts "<img src=\"" + getGraphURLForPlayers(sortedPlayers[startId..endId], ratingFiles, tourneyDate, title) +"\"/>"
	puts "</br></br>"
end
puts "</center>"